<template>
  <div>
    <div class="flex items-center">
      <div class="total">共 {{ total }} 条 </div>
      <div class="w-1px h-16px bg-[#ddd] mx-16px line"></div>
      <div class="flex items-center btnbox">
        <el-button @click="batchActions('remark')" v-if="showBtn('remark')">批量备注</el-button>
        <el-button @click="handleChange" v-if=" props.status != 9">批量变更</el-button>
        <el-button @click="batchActions('uninvalid')" v-if=" props.status == 9">反无效</el-button>
        <el-button @click="batchActions('audit')" v-if="showBtn('audit')">审核通过</el-button>
        <el-button @click="batchActions('waitConfirm')" v-if="showBtn('waitConfirm')">
          转为待确认
        </el-button>
        <el-button @click="batchActions('invalid')" v-if="showBtn('invalid')">无效订单</el-button>
        <el-button @click="batchActions('unsigned')" v-if="showBtn('unsigned')">
          变更未签收
        </el-button>
        <el-button @click="batchActions('signed')" v-if="showBtn('signed')"> 变更已签收 </el-button>
        <el-button @click="batchActions('returnGoods')" v-if="showBtn('returnGoods')">
          退货
        </el-button>
        <el-button @click="batchActions('abnormal')" v-if="showBtn('abnormal')">订单异常</el-button>
        <el-button @click="batchActions('sends')" v-if="showBtn('sends')">发货</el-button>
        <el-button @click="batchActions('cancel')" v-if="showBtn('cancel')">取消订单</el-button>
      </div>
      <div class="w-1px h-16px bg-[#ddd] mx-16px line"></div>
      <div class="text-[#333] text-[14px] flex items-center time">
        <div class="mr-4px">下单时间</div>
        <div class="flex flex-col relative arrowbox" @click="handleSort">
          <Icon
            icon="ep:caret-top"
            :color="sort === 'DESC' ? '#999' : '#333'"
            :size="12"
            class="absolute bottom-[-1px] cursor-pointer"
          />
          <Icon
            icon="ep:caret-bottom"
            :color="sort === 'DESC' ? '#333' : '#999'"
            :size="12"
            class="absolute top-[-1px] cursor-pointer"
          />
        </div>
      </div>
    </div>

    <!-- 批量备注 -->
    <ComfirmPops
      ref="comfirmPopsRef"
      :type="mode === 'batch' ? config[curIndex]?.type : initConfig[curIndex]?.type"
      :showIcon="mode === 'batch' ? config[curIndex]?.showIcon : initConfig[curIndex]?.showIcon"
      :show-dot="mode === 'batch' ? config[curIndex]?.showDot : initConfig[curIndex]?.showDot"
      :title="mode === 'batch' ? config[curIndex]?.title : initConfig[curIndex]?.title"
      :width="mode === 'batch' ? config[curIndex]?.width : initConfig[curIndex]?.width"
      @confirm="batchMark"
    >
      <template #content>
        <div
          class="pl-[20px]"
          v-if="(mode === 'batch' ? config[curIndex]?.type : initConfig[curIndex]?.type) === 'tips'"
        >
          {{
            `确定${mode === 'batch' ? config[curIndex].placeholder : initConfig[curIndex].placeholder}吗?`
          }}
        </div>
        <div class="pl-[20px]" v-else>
          <div
            class="flex items-baseline"
            v-if="actionName === 'abnormal' || actionName === 'invalid'"
          >
            <div class="flex items-center shrink-0 mr-15px lable">
              <div class="txt">{{actionName === 'abnormal' ? '异常原因' : '无效原因'}}</div>
              <div class="red">*</div>
            </div>
            <div class="val" v-if="mode === 'batch'">
              <el-checkbox-group v-model="reasonValue">
                <el-checkbox
                  v-for="(item, index) in config[curIndex]?.list"
                  :key="index"
                  :label="item.label"
                  :value="item.label"
                />
              </el-checkbox-group>
            </div>
            <div class="val" v-else>
              <el-checkbox-group v-model="reasonValue">
                <el-checkbox
                  v-for="(item, index) in initConfig[curIndex]?.list"
                  :key="index"
                  :label="item.label"
                  :value="item.label"
                />
              </el-checkbox-group>
            </div>
          </div>
          <div
            class="flex py-10px cont"
            v-if="actionName === 'remark' || actionName === 'invalid' || actionName === 'abnormal'"
          >
            <div class="label mr-15px text-[13px] shrink-0 lable">备注原因</div>
            <div class="w-full val">
              <el-input
                v-model="remark"
                resize="none"
                type="textarea"
                :rows="6"
                maxlength="200"
                :show-word-limit="true"
                placeholder="请输入备注"
                class="w-full"
              />
            </div>
          </div>
          <div
            class="mt-[10px]"
            :class="actionName === 'abnormal' ? 'flex' : ''"
            v-if="actionName === 'abnormal' || actionName === 'cancel'"
          >
            <div class="flex items-center shrink-0 mr-15px" v-if="actionName === 'abnormal'">
              <div class="txt">订单取消后，采购库存是否对应减少</div>
              <div class="red">*</div>
            </div>
            <div class="text-[#999] text[14px] mb-[20px] desc" v-if="actionName === 'cancel'">
              取消订单后订单状态将变成无效订单，请选择订单取消后： 采购库存是否对应减少
            </div>
            <div class="val">
              <el-radio-group text-color="#3721FF" v-model="cancelRadio">
                <el-radio :value="0">是，减少采购库存</el-radio>
                <el-radio :value="1">否，保留采购库存</el-radio>
              </el-radio-group>
            </div>
           
            <div class="mt-[5px] storelist" v-if="cancelRadio">
              <el-select v-model="storeId" placeholder="请选择仓库">
                <el-option v-for="item in storeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </div>
          <div v-if="actionName === 'unsigned'">
            <div class="text[14px] mb-[20px] desc"> 是否将订单状态变更到未签收？ </div>
            <div class="flex">
              <div class="flex items-center shrink-0 mr-15px">
                <div class="text-[#999] txt">未签收原因</div>
              </div>
              <div class="val">
                <el-radio-group text-color="#3721FF" v-model="reason">
                  <el-radio value="拒收">拒收</el-radio>
                  <el-radio value="退货">退货</el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>
          <div v-if="actionName === 'returnGoods'">
            <div class="text[14px] mb-[20px] desc"> 确定要退货吗？ </div>
            <div>
              <el-checkbox-group v-model="isSaleAfter">
                <el-checkbox :value="1">退货后生成售后订单</el-checkbox>
              </el-checkbox-group>
            </div>
            <div class="text-[#999] text-[12px] desc">若取消选择仅退货不会生成售后订单</div>
          </div>
        </div>
      </template>
    </ComfirmPops>
    <BatchImport
      ref="batchImportRef"
      width="40%"
      title="批量变更签收状态"
      titleDesc="使用场景：1.不走合作物流，标记订单结果（已签收/未签收）；2.订单结果错误变更，签收变未签收，未签收变签收"
      :showDot="true"
      :statusList="statusList"
      :showStatusList="true"
      @downTeamplate="downTeamplates"
      @close="isBatchImport = false"
      @confirm="comfirmImport"
    />
  </div>
</template>

<script setup lang="ts">
import { ElLoading } from 'element-plus'
import * as TradeOrderApi from '@/api/mall/trade/order'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions, DictDataType } from '@/utils/dict'
import { downTeamplate } from '@/utils'
import { PurchaseStoreApi } from '@/api/purchase/warehouse'

const { loadStart, loadDone } = usePageLoading()

type SortType = 'DESC' | 'ASC'
interface OrderData {
  orderNo: any[]
  remark?: string
  invalidReason?: string // 可选属性
  unsignedReason?: string // 可选属性
  status: number
  inventoryFlag?: boolean // 可选属性
  storeId?: number // 可选属性
}
type StoreVO = {
  label:string
  value:number|string
}
const message = useMessage()
const emit = defineEmits(['updateList', 'updateSort', 'updateModeValue'])
defineOptions({ name: 'BatchAction' })
const props = defineProps({
  total: {
    type: Number,
    default: 0
  },
  sort: {
    type: String as () => SortType,
    default: 'DESC'
  },
  selectedRows: {
    type: Array,
    default: () => []
  },
  status: {
    type: Number,
    default: 0
  },
  mode: {
    type: String,
    default: 'batch'
  }
})

const curIndex = ref(0)

const templateUrl = ref('')

const batchImportRef = ref()

const isBatchImport = ref(false)

const isSaleAfter = ref([])

const storeList = ref<StoreVO[]>([])

const storeId = ref<number|string>()

const initConfig = [
  {
    title: '确定提示',
    placeholder: '批量备注',
    code: 'remark',
    type: 'form',
    showDot: false,
    showIcon: true,
    list: [],
    width: '420px',
    showCondition: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  },
  {
    title: '确定提示',
    placeholder: '批量变更',
    code: 'remark',
    type: 'form',
    showDot: false,
    showIcon: true,
    list: [],
    width: '420px',
    showCondition: [5, 6, 7]
  },
  {
    title: '确定提示',
    placeholder: '审核通过',
    code: 'audit',
    type: 'tips',
    showDot: false,
    showIcon: true,
    list: [],
    width: '420px',
    showCondition: [1, 2]
  },
  {
    title: '确定提示 ',
    placeholder: '转为待确认',
    code: 'waitConfirm',
    type: 'tips',
    showDot: false,
    showIcon: true,
    list: [],
    width: '420px',
    showCondition: [1]
  },
  {
    title: '无效订单',
    placeholder: '无效订单',
    code: 'invalid',
    type: 'form',
    showDot: true,
    showIcon: false,
    list: getIntDictOptions(DICT_TYPE.ORDER_INVALID_REASON),
    width: '600px',
    showCondition: [1, 2]
  },
  {
    title: '确定提示',
    placeholder: '变更未签收',
    code: 'unsigned',
    type: 'form',
    showDot: false,
    showIcon: true,
    list: [
      { label: '拒收', value: 1 },
      { label: '退货', value: 2 }
    ],
    width: '420px',
    showCondition: [6]
  },
  {
    title: '确定提示',
    placeholder: '变更已签收',
    code: 'signed',
    type: 'tips',
    showDot: true,
    showIcon: false,
    list: [],
    width: '420px',
    showCondition: [5, 7]
  },
  {
    title: '确定提示',
    placeholder: '退货',
    code: 'returnGoods',
    type: 'form',
    showDot: false,
    showIcon: true,
    list: [],
    width: '420px',
    showCondition: [6]
  },
  {
    title: '订单异常',
    placeholder: '订单异常',
    code: 'abnormal',
    type: 'form',
    showDot: true,
    showIcon: false,
    list: getIntDictOptions(DICT_TYPE.ORDER_ABNORMAL_CAUSES),
    width: '600px',
    showCondition: [5]
  },
  {
    title: '确定提示',
    placeholder: '发货',
    code: 'sends',
    type: 'tips',
    showDot: false,
    showIcon: true,
    list: [],
    width: '420px',
    showCondition: [3, 4]
  },
  {
    title: '确定提示',
    placeholder: '反异常',
    code: 'unabnormal',
    type: 'tips',
    showDot: false,
    showIcon: true,
    list: [],
    width: '420px',
    showCondition: [3, 4]
  },
  {
    title: '确认要取消订单吗？',
    placeholder: '取消订单',
    code: 'cancel',
    type: 'form',
    showDot: false,
    showIcon: false,
    list: [],
    width: '420px',
    showCondition: [3, 4,5],
    desc: '取消订单后订单状态将变成无效订单，请选择订单取消后：采购库存是否对应减少'
  },
  {
    title: '确定提示',
    placeholder: '反无效',
    code: 'uninvalid',
    type: 'tips',
    showDot: false,
    showIcon: true,
    list: [],
    width: '420px',
    showCondition: [9]
  },
]

const config = ref()

const codeList = ['audit', 'waitConfirm', 'sends']

const comfirmPopsRef = ref()

const actionName = ref('')

const batchMarkRef = ref()

const remark = ref('')

const reasonValue = ref([])

const cancelRadio = ref(0)

const reason = ref('拒收')

const statusList = getIntDictOptions(DICT_TYPE.ORDER_STATUS)

const dataInit = () => {
  remark.value = ''
  reasonValue.value = []
  cancelRadio.value = 0
  reason.value = '拒收'
}

const batchActions = (name: string) => {
  if (!props.selectedRows.length) {
    message.error('请选择订单')
    return
  }
  actionName.value = name
  if (props.mode === 'batch') {
    curIndex.value = config.value.findIndex((item) => item.code === name)
  } else {
    curIndex.value = initConfig.findIndex((item) => item.code === name)
  }
  if (curIndex.value === -1) {
    message.error('请选择正确的操作')
    return
  }
  comfirmPopsRef.value?.show()
}

/**
 * 批量备注
 */
const batchMark = async (res: boolean) => {
  const orderNo = props.selectedRows.map((item) => item.orderNo)
  try {
    if (actionName.value === 'remark') {
      if (!remark.value) {
        message.error('请输入备注')
        return
      }
      loadStart()
      await TradeOrderApi.updateOrderRemarkNew({ orderNo, remark: remark.value })
    } else {
      let data: OrderData = {
        orderNo,
        status: 0
      }

      // 根据 actionName 的不同，动态添加属性
      if (actionName.value === 'invalid') {
        if (reasonValue.value.length === 0) {
          message.error('请选择无效原因')
          return
        }
        data.invalidReason = reasonValue.value.join(',')
        data.status = 9
      } else if (actionName.value === 'audit' || actionName.value === 'waitConfirm') {
        data.status = 2
      } else if (actionName.value === 'unsigned') {
        data.unsignedReason = reason.value // 确认这里的 `reason` 是否正确
        data.status = 7
      } else if (actionName.value === 'signed') {
        data.status = 6
      } else if (actionName.value === 'abnormal') {
        if (reasonValue.value.length === 0) {
          message.error('请选择订单异常')
          return
        }
        data.invalidReason = reasonValue.value.join(',')
        data.status = 8
      } else if (actionName.value === 'sends') {
        data.status = 5
      } else if (actionName.value === 'unabnormal') {
        data.status = 1
      } else if (actionName.value === 'returnGoods') {
        if (isSaleAfter.value.length === 1) {
          data.status = 10
        } else {
          data.status = 7
        }
      } else if (actionName.value === 'uninvalid') {
        data.status = 1
      }

      // 处理是否减少库存
      if (
        actionName.value === 'cancel' ||
        actionName.value === 'invalid' ||
        actionName.value === 'abnormal'
      ) {
        data.inventoryFlag = cancelRadio.value ? true : false
        if(cancelRadio.value){
          if(!storeId.value){
            message.error('请选择仓库')
            return
          }
          data.storeId = Number(storeId.value)
        }
      }
      data.remark = remark.value

      // 继续处理 data（例如发送请求）
      loadStart()
      if (res || codeList.indexOf(actionName.value) === -1) {
        if (actionName.value === 'audit') {
          await TradeOrderApi.approvedOrder(data)
        } else {
          await TradeOrderApi.updateOrderStatus(data)
        }
      }
    }

    message.success('操作成功')
    emit('updateList')
    dataInit()
    comfirmPopsRef.value?.hide()
  } finally {
    loadDone()
  }
}

/**
 * 从config中判断是否显示对应的按钮
 */
const showBtn = (btn: string) => {
  return config.value.some((item) => item.code === btn) ? true : false
}

/**
 * 根据传入的状态值，获取不同的config
 */
watch(
  () => props.status,
  (newVal) => {
    curIndex.value = 0
    config.value = initConfig.filter((item) => item.showCondition.includes(newVal))
  },
  { immediate: true, deep: true }
)

/**
 * 显示导入
 */
const handleChange = () => {
  batchImportRef.value?.show()
}

/**
 * 下载模板
 */
const downTeamplates = async () => {
  if (!templateUrl.value) {
    message.warning('暂无模板')
    return
  }
  downTeamplate(templateUrl.value, '批量变更签收状态模板.xlsx')
}

/**
 * 导入
 */
const comfirmImport = async (val: any) => {
  try {
    loadStart()
    await TradeOrderApi.importProductOrderStatus(val.file, {
      status: val.statusValue
    })
    message.success('导入成功')
  } catch (e) {
    message.error(e.msg)
  } finally {
    loadDone()
  }
}

const handleSort = () => {
  emit('updateSort', props.sort === 'DESC' ? 'ASC' : 'DESC')
}

const init = async () => {
  const res = await PurchaseStoreApi.getPurchaseStorePage({pageNo:1, pageSize: 1000})
  storeList.value = res.list.map(item=>{
    return {
      label: item.storeName,
      value: item.id
    }
  })
}


onMounted(() => {
  init()
})

defineExpose({
  batchActions
})
</script>

<style lang="scss" scoped>
:deep(.el-button) {
  border-radius: 10px;
}
</style>
